package com.example.e_comm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.e_comm.entity.Permission;
import com.example.e_comm.entity.Role;
import com.example.e_comm.entity.RolePermission;
import com.example.e_comm.mapper.RoleMapper;
import com.example.e_comm.mapper.RolePermissionMapper;
import com.example.e_comm.service.PermissionService;
import com.example.e_comm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper mapper;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public void assignPermission(Long roleId, List<Long> pIds) {
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        if (pIds != null && !pIds.isEmpty()){
            List<RolePermission> rps = pIds.stream()
                    .map(pId -> {
                        RolePermission rp = new RolePermission();
                        rp.setRoleId(roleId);
                        rp.setPermissionId(pId);
                        return rp;
                    }).collect(Collectors.toList());
            for (RolePermission rp : rps){
                rolePermissionMapper.insert(rp);
            }
        }
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return mapper.getRolesByUserId(userId);
    }

    @Override
    public Role getRoleWithPermissions(Long roleId) {
        Role role = this.getById(roleId);
        if (role != null){
            List<Permission> permissions = permissionService.getPermissionByRoleId(roleId);
            role.setPermissions(permissions);
        }
        return role;
    }

    @Override
    public IPage<Role> search(Page<Role> page,
                              com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Role> wrapper) {
        return this.page(page, wrapper);
    }
}